package com.admin.web.controller;

import com.admin.web.uresponse.OBGUserResponse;
import com.bayss.core.DokoServerException;
import com.bayss.core.DokoServerExceptionFactor;
import com.bayss.core.constant.ResultMsg;
import com.bayss.core.entity.code.CodeBase;
import com.bayss.core.enums.HandleCode;
import com.bayss.core.enums.OrderOp;
import com.bayss.core.model.OrderMsg;
import com.bayss.core.model.ProcessInfo;
import com.bayss.core.service.code.CodeBaseService;
import com.bayss.core.service.order.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 后台订单操作
 *
 * @author yangjian
 */
@RestController
public class OrderController extends ApiBaseController {

    private final OrderService orderService;

    private final CodeBaseService codeBaseService;

    private static final ThreadLocal<DateFormat> DATE_FORMAT_TO_YMD = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));


    @Autowired
    public OrderController(OrderService orderService, CodeBaseService codeBaseService) {
        this.orderService = orderService;
        this.codeBaseService = codeBaseService;
    }

    /**
     * 商家接单池
     */
    @GetMapping("/order/search.json")
    public ResultMsg poolRevc(@RequestParam(name = "orderNo", required = false) String orderNo,
                              @RequestParam(name = "userName", required = false) String userName,
                              @RequestParam(name = "stationId", required = false) Long stationId,
                              @RequestParam(name = "orderType", required = false) Integer orderType,
                              @RequestParam(name = "channel", required = false) Integer channel,
                              @RequestParam(name = "orderStatus", required = false) Integer orderStatus,
                              @RequestParam(name = "start_time", required = false) String startTime,
                              @RequestParam(name = "end_time", required = false) String endTime,
                              @RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                              @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        long start = 0;
        long end = 0;
        try {
            DateFormat dateFormat = DATE_FORMAT_TO_YMD.get();
            if (StringUtils.isNotBlank(startTime)) {
                Date startDate = dateFormat.parse(startTime);
                start = startDate.getTime();
            }
            if (StringUtils.isNotBlank(endTime)) {
                Date endDate = dateFormat.parse(endTime);
                end = endDate.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ResultMsg.success(orderService.getOrderByPage(orderNo, userName, stationId, orderType, channel, orderStatus, start, end, page, pageSize));
    }

    /**
     * 商家接单池
     */
    @GetMapping("/order/pool/revc.json")
    public ResultMsg poolRevc(@RequestParam(name = "stationId") Long stationId,
                              @RequestParam(name = "maxId", required = false, defaultValue = "0") Long maxId,
                              @RequestParam(name = "count", required = false, defaultValue = "10") Integer count) {
        return ResultMsg.success(orderService.getOrdersByPool(stationId, HandleCode.NEW, maxId, count));
    }

    /**
     * 商家派单池
     */
    @GetMapping("/order/pool/tran.json")
    public ResultMsg poolTran(@RequestParam(name = "stationId") Long stationId,
                              @RequestParam(name = "maxId", required = false, defaultValue = "0") Long maxId,
                              @RequestParam(name = "count", required = false, defaultValue = "10") Integer count) {
        return ResultMsg.success(orderService.getOrdersByPool(stationId, HandleCode.TRANIING, maxId, count));
    }

    /**
     * 商家接单上报
     */
    @RequestMapping("/order/pool/submit.json")
    public ResultMsg submit(@RequestParam(name = "orderId") Long orderId) {
        return ResultMsg.success(orderService.submit(orderId));
    }

    /**
     * 确认送达 (订单完成)
     */
    @PostMapping("/order/send_ack.json")
    public ResultMsg sendAck(@RequestParam(name = "orderNo") String orderNo,
                             @RequestParam(name = "revcCode", required = false, defaultValue = "") String revcCode) {
        ProcessInfo processInfo = ProcessInfo.builder()
                .orderNo(orderNo)
                .revcCode(revcCode)
                .build();
        OrderMsg<String> res = orderService.handlerOrder(OrderOp.ORDER_SENDED, processInfo);
        if (res.isOk()) {
            return ResultMsg.success();
        }
        throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "确认送达失败");
    }

    /**
     * 派单
     */
    @PostMapping("/order/transfer.json")
    public ResultMsg transfer(@RequestParam(name = "orderNo") String orderNo,
                              @RequestParam(name = "hId") Long hid) {
        ProcessInfo processInfo = ProcessInfo.builder()
                .orderNo(orderNo)
                .hid(hid)
                .build();
        OrderMsg<String> res = orderService.handlerOrder(OrderOp.ORDER_TRAN, processInfo);
        if (res.isOk()) {
            return ResultMsg.success();
        }
        throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "商户派单失败");
    }

    /**
     * 退款审核
     */
    @PostMapping("/order/refund_check.json")
    public ResultMsg refundCheck(OBGUserResponse userResponse,
                                 @RequestParam(name = "orderNo") String orderNo,
                                 @RequestParam(name = "op") Integer op,
                                 @RequestParam(name = "refundMoney", required = false, defaultValue = "0") Integer refundMoney) {
        String opName = userResponse.getObgUserInfo().getAccount();
        int opId = userResponse.getUid();
        return ResultMsg.success(orderService.refundCheck(orderNo, op, opId, opName, refundMoney));
    }

    /**
     * 获取评价信息
     */
    @GetMapping("/order/comment/get.json")
    public ResultMsg getComments(@RequestParam(name = "stationId", required = false, defaultValue = "-1") Long stationId,
                                 @RequestParam(name = "status", required = false, defaultValue = "-1") Integer status,
                                 @RequestParam(name = "display", required = false, defaultValue = "-1") Integer display,
                                 @RequestParam(name = "page", required = false, defaultValue = "1") Integer page,
                                 @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        return ResultMsg.success(orderService.getComments(stationId, status, display, page, pageSize));
    }

    /**
     * 获取评价信息
     */
    @GetMapping("/order/comment/set.json")
    public ResultMsg setComment(@RequestParam(name = "orderNo") String orderNo,
                                @RequestParam(name = "status") int status,
                                 @RequestParam(name = "display") int display) {
        return ResultMsg.success(orderService.setComment(orderNo, status, display));
    }

    /**
     * 订单详情
     */
    @RequestMapping("/order/desc.json")
    public ResultMsg orderDesc(@RequestParam(name = "orderNo") String orderNo) {
        return ResultMsg.success(orderService.getOrderDesc(orderNo));
    }

    /**
     * 获取评价信息
     */
    @GetMapping("/order/refund_reason/get.json")
    public ResultMsg getRefundReason() {
        return ResultMsg.success(codeBaseService.getCodesValueByCode("refund_reason"));
    }

    /**
     * 获取评价信息
     */
    @GetMapping("/order/refund_reason/add.json")
    public ResultMsg addRefundReason(@RequestParam(name = "obgValue") String obgValue,
                                @RequestParam(name = "obgDesc") String obgDesc) {
        CodeBase codeBase = new CodeBase();
        codeBase.setObgKey("refund_reason");
        codeBase.setObgValue(obgValue);
        codeBase.setObgDesc(obgDesc);
        return ResultMsg.success(codeBaseService.add(codeBase));
    }

    /**
     * 删除评价信息
     */
    @GetMapping("/order/refund_reason/del.json")
    public ResultMsg delGetRefundReason(@RequestParam(name = "id") Integer id) {
        return ResultMsg.success(codeBaseService.del(id));
    }
}
